package com.jeln.web.admin;

import com.jeln.po.User;
import com.jeln.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

//登录控制器
@Controller
@RequestMapping("admin")
public class LoginController {

    @Autowired
    private UserService userService;

    //默认跳转登录页面
    @GetMapping
    public String loginPage(){
        return "admin/login";
    }

    //登录验证，成功则跳转到index页面
    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes){
        User user = userService.checkUser(username,password);
        //如果用户名和密码正确
        if (user != null){
            //不把密码传到前面，否则不安全
            user.setPassword(null);
            //把返回的user放到session里面
            session.setAttribute("user",user);
            return "admin/index";
        }else{
            //用户密码不对，给前端提示
            attributes.addFlashAttribute("message","用户名或密码错误");
            //重定向到login页面
            return "redirect:/admin";
        }
    }

    //注销
    @GetMapping("/logout")
    public String logout(HttpSession session){
        //注销，把session传过去的user拿掉
        session.removeAttribute("user");
        return "redirect:/admin";
    }

}
